package com.atguigu.gmall.order.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.rabbit.service.MsgRetryService;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class OrderPayedQueueListener {

    @Autowired
    private OrderInfoService orderInfoService ;

    @Autowired
    private MsgRetryService msgRetryService ;

    @RabbitListener(queues = "order.payed.queue")
    public void orderPayedQueueListener(Message message , Channel channel) {

        // 获取消息的标签
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        // 获取消息内容
        byte[] body = message.getBody();
        String msg = new String(body) ;

        try {

            Map<String , String> map = JSON.parseObject(msg, Map.class);

            // 更改订单的状态
            orderInfoService.orderPayedUpateOrderStatus(map) ;

            // 进行手动应答
            channel.basicAck(deliveryTag , true);

        } catch (IOException e) {
            e.printStackTrace();
            msgRetryService.msgRetry(msg , deliveryTag , channel , 5);
        }

    }

}
